package org.jeecg.modules.flowable.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.flowable.entity.FlowCategory;
import org.jeecg.modules.flowable.mapper.FlowCategoryMapper;
import org.jeecg.modules.flowable.service.FlowCategoryService;
import org.jeecg.modules.flowable.utils.BeanUtils;
import org.jeecg.modules.flowable.vo.FlowCategoryVO;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class FlowCategoryServiceImpl extends ServiceImpl<FlowCategoryMapper, FlowCategory> implements FlowCategoryService {

    @Override
    public boolean save(FlowCategory entity) {
        if (Objects.nonNull(entity.getParentId())) {
            FlowCategory parentCategory = this.getById(entity.getParentId());
            if (Objects.isNull(parentCategory)) {
                throw new JeecgBootException("新增流程分类失败，找不到对应分类上级！");
            }
            entity.setHierarchy(parentCategory.getHierarchy() + 1);
        }
        if (Objects.isNull(entity.getHierarchy())) {
            entity.setHierarchy(1);
        }
        if (Objects.isNull(entity.getParentId())) {
            entity.setParentId(0L);
        }
        if (Objects.isNull(entity.getFrontShow())) {
            entity.setFrontShow(Boolean.TRUE);
        }
        if (Objects.isNull(entity.getSeqNo())) {
            entity.setSeqNo(1);
        }
        return super.save(entity);
    }

    @Override
    public List<FlowCategoryVO> queryList() {
        List<FlowCategory> list = this.list();
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        // 类型转换
        List<FlowCategoryVO> voList = BeanUtils.convertListTo(list, FlowCategoryVO::new);
        Optional<Integer> maxLevelOptional = voList.stream().map(FlowCategoryVO::getHierarchy).max(Integer::compareTo);
        if (!maxLevelOptional.isPresent()) {
            return new ArrayList<>();
        }
        List<FlowCategoryVO> resultList = voList.stream().filter(e -> e.getParentId().equals(0L)).collect(Collectors.toList());
        // 递归完成级联排序
        cascadeList(resultList, voList);
        return resultList;
    }

    /**
     * 递归完成级联排序
     *
     * @param resultList 顶级节点
     * @param list       全部节点
     */
    private void cascadeList(List<FlowCategoryVO> resultList, List<FlowCategoryVO> list) {
        if (CollectionUtils.isEmpty(resultList)) {
            return;
        }
        resultList.forEach(e -> {
            List<FlowCategoryVO> subList = list.stream().filter(s -> s.getParentId().equals(e.getId())).collect(Collectors.toList());
            e.setSubCategoryList(subList);
            cascadeList(subList, list);
        });
    }
}
